
import paramiko
import re
"""
检测SSH 是否只允许密钥登录
"""
def checkSSHpublickey(host, port ):

    try:
        # 建立连接
        trans = paramiko.Transport((host, 22))
        trans.connect(username="root", password="you_passwd")

        # 将sshclient的对象的transport指定为以上的trans
        ssh = paramiko.SSHClient()
        ssh._transport = trans

        # 剩下的就和上面一样了
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -l")
        print(ssh_stdout.read())

        # 关闭连接
        trans.close()
    except paramiko.ssh_exception.AuthenticationException as e:
        print("密码认证登录-认证失败",e)
        pattern = ".*publickey.*"
        if len(re.findall(pattern,str(e))) != 0:
            print("只允许密钥登录",host)
            return True
        else:
            print("允许密码登录",host)
            return False
    # except paramiko.ssh_exception.SSHException as e:
    #     print("无法通讯",e)



host = "192.168.42.200"
port = 22
checkSSHpublickey(host, port)
